package com.wcar.font.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.wcar.common.vo.Result;
import com.wcar.font.gateway.vo.WhiteList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

@Component
public class LoginFilter implements GlobalFilter, Ordered {
    @Autowired
    private WhiteList whiteList;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //1.获取请求路径
        String path = request.getPath().toString();
        System.out.println(path);
        //2. 判断该路径是否属于白名单--
        if(whiteList.getUrl().contains(path)){
              //3.放行
              return chain.filter(exchange);
        }
        //4. 获取请求头的指定内容
        String token = request.getHeaders().getFirst("token");
        //5. 判断token是否为空以及token是否正确
        if(StringUtils.hasText(token)&&redisTemplate.hasKey("font:login:"+token)){
            //刷新token
            ValueOperations<String,String> valueOperations = redisTemplate.opsForValue();
            String o = valueOperations.get("font:login:" + token);
            valueOperations.set("font:login:" + token,o,30, TimeUnit.MINUTES);
            //4.放行
            return chain.filter(exchange);
        }
        //返回一个json数据。
        Result<String> result=new Result<>(500,"未登录",null);
        byte[] bytes = JSON.toJSONString(result).getBytes(StandardCharsets.UTF_8);
        //3.4调用bufferFactory方法,生成DataBuffer对象
        DataBuffer buffer = response.bufferFactory().wrap(bytes);
        //4.调用Mono中的just方法,返回要写给前端的JSON数据
        return response.writeWith(Mono.just(buffer));
    }

    //优先级:值越小优先级越高
    @Override
    public int getOrder() {
        return 0;
    }
}
